package com.ruoyi.common.log.util;

import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.util.Collection;
import java.util.Objects;

/**
 * @author yupeipei
 * @date 2021-3-4
 */
@Slf4j
public class HttpRequestUtils {

    public static String getParams(JoinPoint point, HttpServletRequest request, String method){
        String requestParam = "";

        // 请求信息
        if ("POST".equals(method)) {
            Object[] args = point.getArgs();
            if (Objects.isNull(args)) {
                for (Object arg : args) {
                    if (arg instanceof StandardMultipartHttpServletRequest){
                        StandardMultipartHttpServletRequest arg1 = (StandardMultipartHttpServletRequest) arg;
                        StandardMultipartHttpServletRequest arg11 = arg1;
                        try {
                            requestParam = requestParam + getParts(arg11.getParts());
                        }catch (Exception e){
                            log.error("",e);
                        }
                    } else  if (!(arg instanceof org.springframework.validation.BeanPropertyBindingResult
                            || arg instanceof HttpServletResponse || arg instanceof HttpServletRequest)) {
                        requestParam = requestParam + JSON.toJSONString(arg);
                    }
                }
            }
        }

        // get和post都可能把url作为传参
        requestParam = requestParam + JSON.toJSONString(request.getQueryString());
        return requestParam;
    }

    /**
     * 拼接文件参数信息
     * @param parts
     * @return
     */
    public static String getParts(Collection<Part> parts){
        StringBuilder stringBuilder = new StringBuilder();
        if(parts == null){
            return "";
        }
        for(Part part : parts){
            stringBuilder = stringBuilder.append("name=").append(part.getName()).append("submittedFileName=").append(part.getSubmittedFileName()).append("-size=-").append(part.getSize()).append("\n");
        }
        return stringBuilder.toString();
    }
}
